package planner
import grails.converters.*

class AirportController {
  def geocoderService
  def scaffold=true
  def map = {
    [airportList: Airport.list()]
  }
  
  def getXml = {
    render Airport.findByIata(params.iata) as XML
  }
              
  def getJson = {
    def airport = Airport.findByIata(params.iata)  
    if(!airport){
      airport = new planner.Airport(iata:params.iata, name:"Not found")
    }
    render airport as JSON
  }      
  def geocode = {
    def result = geocoderService.geocodeAirport(params.iata)
    render result as JSON
  }
  
  def save = {
    def results = geocoderService.geocodeAirport(params.iata)    
    def airport = new Airport(params + results)
    if(!airport.hasErrors() && airport.save()) {
        flash.message = "Airport ${airport.id} created"
        redirect(action:show,id:airport.id)
    }
    else {
        render(view:'create',model:[airport:airport])
    }
  }
  
  def update = {
    def airport = Airport.get( params.id )
    if(airport) {
        def results = geocoderService.geocodeAirport(params.iata)    
        airport.properties = params + results
        if(!airport.hasErrors() && airport.save()) {
            flash.message = "Airport ${params.id} updated"
            redirect(action:show,id:airport.id)
        }
        else {
            render(view:'edit',model:[airport:airport])
        }
    }
    else {
        flash.message = "Airport not found with id ${params.id}"
        redirect(action:edit,id:params.id)
    }
  }
  
  def mlist = {
    if(!params.max) params.max = 5
    [airportList:Airport.list(params)]
  }
  
  def xmlList = {
    render Airport.list() as XML
  }

  def xmlShow = {
    render Airport.get(params.id) as XML
  }
  
  def customXmlList = {
    def list = Airport.list()
      render(contentType:"text/xml"){
        airports{
          for(a in list){
            airport(id:a.id, iata:a.iata){
              "official-name"(a.name)
              city(a.city)
              state(a.state)
              country(a.country)
              location(latitude:a.lat, longitude:a.lng)
            }
          }        
        }
      }
    }

  def debugAccept = {
    def clientRequest = request.getHeader("accept")
    def serverResponse = request.format
    render "Client: ${clientRequest}\nServer: ${serverResponse}\n"    
  }
  
  def list = {
    if(!params.max) params.max = 10
    def list = Airport.list(params)
    withFormat{
      html{
        return [airportInstanceList:list,airportInstanceTotal:list.size()]
      }
      xml{
        render list as XML
      }
    }
  }
    
  def index = {       
    switch(request.method){
      case "POST":
        def airport = new Airport(params.airport)        
        if(airport.save()){
          response.status = 201 // Created
          render airport as XML
        }
        else{
          response.status = 500 //Internal Server Error
          render "Could not create new Airport due to errors:\n ${airport.errors}"
        }
        break
      case "GET":        
        if(params.iata){render Airport.findByIata(params.iata) as XML}
        else{render Airport.list() as XML}                          
        break
      case "PUT":
        def airport = Airport.findByIata(params.airport.iata)
        airport.properties = params.airport
        if(airport.save()){
          response.status = 200 // OK
          render airport as XML
        }
        else{
          response.status = 500 //Internal Server Error
          render "Could not create new Airport due to errors:\n ${airport.errors}"
        }          
        break
      case "DELETE":        
        if(params.iata){
          def airport = Airport.findByIata(params.iata)
          if(airport){
            airport.delete()
            render "Successfully Deleted."
          }
          else{
            response.status = 404 //Not Found
            render "${params.iata} not found."
          }
        }
        else{
          response.status = 400 //Bad Request
          render """DELETE request must include the IATA code
                  Example: /rest/airport/iata
          """
        }                
        break
      }   
  }
  
}
